﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using MQTT.Server.Host.Controller;
using MQTT.Server.Host.Entity;

namespace MQTT.Server.Host
{
    /// <summary>
    /// WinAddDevice.xaml 的交互逻辑
    /// </summary>
    public partial class WinAddDevice : Window
    {
        private ObservableCollection<DataModelEntity> dataModels = new ObservableCollection<DataModelEntity>();
        public WinAddDevice()
        {
            InitializeComponent();
            // 绑定数据源
            lvDataModels.ItemsSource = dataModels;
        }

        private void BtnCancel_OnClick(object sender, RoutedEventArgs e)
        {
            DialogResult = false;
        }

        private void BtnDataModelAdd_OnClick(object sender, RoutedEventArgs e)
        {
            WinAddDataNodeTag win = new WinAddDataNodeTag();
            win.Owner = this;
            win.WindowStartupLocation = WindowStartupLocation.CenterOwner;
            if (win.ShowDialog() == true)
            {
                // 添加数据源
                dataModels.Add(new DataModelEntity {Tag = win.Tag, Unit = win.DataModel.Unit, DataType = win.DataModel.Name, DataTypeId = win.DataModel.Id});
            }
        }

        private void btnOk_Click(object sender, RoutedEventArgs e)
        {
            // 获取设备名称
            string name = inputDeviceName.Text;

            // 插入设备到数据库
            int deviceId = DataController.AddDevice(name);

            // 添加数据点
            foreach (var dataModel in dataModels)
            {
                var addDataTag = DataController.AddDataTag(deviceId, dataModel.Tag, dataModel.DataTypeId);
            }

            DialogResult = true;
        }

        private void BtnDataModelRemove_OnClick(object sender, RoutedEventArgs e)
        {
            // 获取选中项 判断是否为空
            var dataModel = lvDataModels.SelectedItem as DataModelEntity;
            if (dataModel != null)
            {
                dataModels.Remove(dataModel);
            }
        }

        private void LvDataModels_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // 获取选中项 判断是否为空
            var dataModel = lvDataModels.SelectedItem as DataModelEntity;
            btnDataModelRemove.IsEnabled = dataModel != null;
        }
    }
}
